package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author GLoRy
 * @date 2021/5/22 15:25
 */
public class GlrApplicationContext {

    /**
     * 表示spring的配置类
     */
    private Class<?> configClass;

    /**
     * 单例池
     */
    private final ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    /**
     * 原型bean定义
     */
    private final ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    /**
     * bean后处理器列表
     */
    private final List<ReBeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    /**
     * 构造方法
     *
     * @param configClass 配置类
     */
    public GlrApplicationContext(Class<com.glr.AppConfig> configClass) {
        this.configClass = configClass;

        /*
         * 解析配置类
         * MyComponentScan注解 --> 扫描路径 --> 扫描 --> BeanDefinition --> beanDefinitionMap
         */
        scan(configClass);

        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if ("singleton".equals(beanDefinition.getScope())) {
                //单例bean对象
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class<?> clazz = beanDefinition.getClazz();

        try {
            //调用无参构造方法反射得到实例对象
            Object instance = clazz.getConstructor().newInstance();

            //依赖注入，对对象属性进行赋值
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(ReAutowired.class)) {
                    Object bean = getBean(declaredField.getName());
                    //设置可访问性
                    declaredField.setAccessible(true);
                    //注入属性值
                    declaredField.set(instance, bean);
                }
            }

            //Aware回调
            if (instance instanceof ReBeanNameAware) {
                ((ReBeanNameAware) instance).setBeanName(beanName);
            }

            //初始化前处理
            for (ReBeanPostProcessor reBeanPostProcessor : beanPostProcessorList) {
                instance = reBeanPostProcessor.postProcessorBeforeInitialization(instance, beanName);
            }

            //初始化
            if (instance instanceof ReInitializingBean) {
                try {
                    ((ReInitializingBean) instance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //初始化后处理
            for (ReBeanPostProcessor reBeanPostProcessor : beanPostProcessorList) {
                instance = reBeanPostProcessor.postProcessorAfterInitialization(instance, beanName);
            }

            //BeanPostProcessor

            return instance;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class<com.glr.AppConfig> configClass) {
        ReComponentScan componentScanAnnotation = configClass.getDeclaredAnnotation(ReComponentScan.class);
        //扫描路径：比如包名com.glr.service
        String path = componentScanAnnotation.value();
        path = path.replace(".", "/");
        //app
        ClassLoader classLoader = GlrApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        //断言目录不为空
        assert resource != null;
        //获取目录
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            assert files != null;
            for (File f : files) {
                //获取绝对路径
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    //从绝对路径中截取字符串
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    //将绝对路径中的 "\\" 替换成 "." 的形式
                    className = className.replace("\\", ".");

                    try {
                        Class<?> clazz = classLoader.loadClass(className);
                        //判断注解是否存在
                        if (clazz.isAnnotationPresent(ReComponent.class)) {
                            //表示当前这个类是一个bean
                            //还需要解析类，判断当前的bean是单例bean，或是prototype类型的bean --> BeanDefinition对象

                            //判断clazz对象是否实现了ReBeanPostProcessor接口
                            if (ReBeanPostProcessor.class.isAssignableFrom(clazz)) {
                                //如若实现接口，实例化对象
                                ReBeanPostProcessor instance = (ReBeanPostProcessor) clazz
                                        .getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }

                            ReComponent componentAnnotation = clazz.getDeclaredAnnotation(ReComponent.class);
                            String beanName = componentAnnotation.value();
                            //bean定义对象
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if (clazz.isAnnotationPresent(ReScope.class)) {
                                ReScope scopeAnnotation = clazz.getDeclaredAnnotation(ReScope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            } else {
                                beanDefinition.setScope("singleton");
                            }

                            beanDefinitionMap.put(beanName, beanDefinition);
                        }

                    } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                            InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    /**
     * getBean方法
     *
     * @param beanName bean的名称
     * @return bean对象
     */
    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            //判断定义的bean如果是singleton，返回返回单例beanName
            String singletonStr = "singleton";
            if (singletonStr.equals(beanDefinition.getScope())) {
                return singletonObjects.get(beanName);
            } else {
                //返回创建原型Bean
                return createBean(beanName, beanDefinition);
            }
        } else {
            //不存在对应的bean
            throw new NullPointerException();
        }
    }
}
